package com.datas.service;

import com.datas.db.hibernatebeans.UmsSysLog;
import com.datas.db.hibernatebeans.UmsUserLoginToken;
import com.datas.utils.hbn.HbnTxRuner;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by jige0727 on 2017/5/4.
 * 日志
 */
@Service
public class LogService {

    /**
     * 插入一个登录日志
     *
     * @param username
     * @param token
     * @param remoteAddr
     * @return
     */
    public Integer saveNewLoginEvent(String username, UmsUserLoginToken token, String remoteAddr) {
        Integer userid = (Integer) new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                String hql = "select u.id from UmsUser u where u.disabled =0 and u.username=:username";
                return getCurrentSession().createQuery(hql)
                        .setParameter("username", username)
                        .uniqueResult();
            }
        }.run();
        UmsSysLog log2Save = new UmsSysLog();
        log2Save.setActType(UmsSysLog.LOG_TYPE_LOGIN);
        log2Save.setActorUserId(userid);
        log2Save.setActorIp(remoteAddr);
        if (token == null) {
            log2Save.setActResult(UmsSysLog.LOG_RESULT_FAIL);
        } else {
            log2Save.setActResult(UmsSysLog.LOG_RESULT_SUCCESS);
        }
        return saveNew(log2Save);
    }

    /**
     * 新建一个日志
     *
     * @return
     */
    public Integer saveNew(UmsSysLog log2Save) {
        Integer res = (Integer) new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                getCurrentSession().save(log2Save);
                return 1;
            }
        }.run();
        return res;
    }

    /**
     * 查询日志列表
     *
     * @return
     */
    public List<UmsSysLog> list() {
        return null;
    }

}
